<?php
namespace app\admin\controller;

use think\Config;
use think\Request;
class Site extends Base
{
	public function index()
	{
		
		$data['sites'] = Config::get('sites');
		$data['wx'] = Config::get('wx');
		return $this->fetch('index',$data);
	}

	/**
	 * 编辑
	 * @return [type] [description]
	 */
	function edit(){
		$param = Request()->post();
		$wx = Config::get('wx');
		$sites = Config::get('sites');
		$re = false;
		if (isset($param['wx'])) {
			$this->merge($wx,$param['wx']);
			$re = $this->save('wx',$wx);
		}
		if (isset($param['sites'])) {
			$this->merge($sites,$param['sites']);
			$re = $this->save('sites',$sites);
		}
		if ($re) {
			$this->success('保存成功');
		}else{
			$this->error('保存失败');
		}
	}

	/**
	 * 递归合并
	 * @param  [type] &$arr [description]
	 * @param  [type] $n    [description]
	 * @return [type]       [description]
	 */
	function merge(&$arr,$n){
		foreach ($n as $k => $v) {
			if (is_array($v)) {
				$this->merge($arr[$k],$v);
			}else{
				$arr[$k] = $v;
			}
		}
	}

	/**
	 * 将数组保存为文件
	 * @param  string $name [description]
	 * @param  array  $data [description]
	 * @return [type]       [description]
	 */
	function save($name='',$data=[])
	{
		if (empty($name) || empty($data)) {
			return false;
		}
		$path = realpath(APP_PATH).DS.'extra';
		if (!file_exists($path)) {
			mkdir($path,0777,true);
		}
		$content = '<?php return '.var_export($data,true) .';';
		$re = file_put_contents($path.DS.$name.EXT,$content);
		if ($re>0) {
			return true;
		}else{
			return false;
		}
	}
}